//
//  AppDelegate.m
//  000-ChatChair
//
//  Created by 李晓东 on 2018/4/16.
//  Copyright © 2018年 PeanutXu. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate () <XMPPStreamDelegate>
@property (nonatomic, strong) XMPPReconnect *xmppReconnect;
@end

@implementation AppDelegate{
    BOOL _isRegister;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)setupStream {
    
    self.queue = dispatch_get_global_queue(0, 0);
//    self.queue = dispatch_get_main_queue();
    self.historyMessage = [NSMutableDictionary dictionary];
    self.xmppStream = [[XMPPStream alloc]init];
    [self.xmppStream addDelegate:self delegateQueue:self.queue];
    [_xmppStream setKeepAliveInterval:30];
    [_xmppStream setEnableBackgroundingOnSocket:YES];
    
    _xmppReconnect = [[XMPPReconnect alloc] initWithDispatchQueue:self.queue];
    [_xmppReconnect setAutoReconnect:YES];
    [_xmppReconnect activate:_xmppStream];

}

- (void)connect:(BOOL)isRegist{
    [self setupStream];
    _isRegister = isRegist;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userKey = [userDefaults objectForKey:USER_KEY];
    NSString *serverKey = [userDefaults objectForKey:SERVER_KEY];
    NSString *portKey = [userDefaults objectForKey:@"port"];
    
    // --------------------- temp code -----------------------
    if (userKey == nil || userKey.length == 0) {
        userKey = @"li";
    }
    if (serverKey == nil || serverKey.length == 0) {
        serverKey = @"192.168.1.100";

    }
    
    //
    if ([self.xmppStream isConnected]) {
        [self goOffline];
        [self.xmppStream disconnect];
    }
    
    if (userKey == nil || userKey.length == 0
        || serverKey == nil || serverKey.length == 0){
        return;
    } else {
        NSString *demoStr = [NSString stringWithFormat:@"%@%@", userKey, HOST_SUFFIX];
        [self.xmppStream setMyJID:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@%@", userKey, HOST_SUFFIX]]];
        [self.xmppStream setHostName:serverKey];
        if (portKey != nil && portKey.length > 0) {
            [self.xmppStream setHostPort:portKey];

        }
        NSError *error;
        [self.xmppStream connectWithTimeout:3 error:&error];
        if (error == nil) {
            NSLog(@"-------connect方法执行完成！！！------");
        } else {
            NSLog(@"连接服务器出现错误%@", error);
        }
    }
    
}

//------------------XMPPStreamDelegate代理中的方法--------------—
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error{
    NSLog(@"收到错误");
}

-(void)xmppStream:(XMPPStream *)sender socketDidConnect:(id)socket{
    NSLog(@"底层网络 socket 连接成功");
}

- (void)xmppStreamConnectDidTimeout:(XMPPStream *)sender{
    NSLog(@"连接超时");
}

- (void)xmppStreamDidConnect:(XMPPStream *)sender{
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:PASS_KEY];
    if (password == nil || password.length == 0) {
        password = @"123";
        
    }
    NSError *error;
    if (_isRegister) {
        [self.xmppStream registerWithPassword:password error:&error];
        
    } else {
        [self.xmppStream authenticateWithPassword:password error:&error];
        
    }
}
// -------------------注册或登录后,不管有没有成功都会调用以下方法--------------------
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    [self goOnline];
    // 调用loginRegistDelegate的loginSuccess显示登录成功
    [self.loginRegistDelegate loginSuccess];
}

- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(id)error{
    NSLog(@"%@", error);
    NSLog(@"连接超时");
}

- (void)xmppStreamDidRegister:(XMPPStream *)sender{
    
}

- (void)xmppStream:(XMPPStream *)sender didSendPresence:(XMPPPresence *)presence{
    NSLog(@"done");
}

// -------------------收到好友上线/下线的消息--------------------
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence{
    NSString *type = presence.type;
    // 当前用户
    NSString *userId = sender.myJID.user;
    // 获取发送消息的用户
    NSString *presenceFromUser = presence.from.user;
    // 不是当前用户发送的消息 && 不是离开房间的消息
    if (![userId isEqualToString:presenceFromUser] && ![presence.from.domain isEqualToString:ROOM_SUFFIX]) {
        
        if ([type isEqualToString:@"available"]) {
            [_rosterListDelegate onOrOff:presence.from.user isOn:YES];
        } else if ([type isEqualToString:@"unavailable"]) {
            [_rosterListDelegate onOrOff:presence.from.user isOn:NO];
        }
    }

}

- (void)xmppStream:(XMPPStream *)sender didNotRegister:(id)error{
    NSLog(@"%@", error);
    NSLog(@"连接超时");
}

// --------------------查询聊天室记录,服务器返回结果--------------------
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq{
    NSString* from = [iq fromStr];  // 获取iq的来源
    NSString* to = [iq to].user;  // 获取iq的发送目标
    NSString* userId = sender.myJID.user;
    // 如果from来自conference.yeeku-pro.local，则表明信息是聊天室信息
    if ([userId isEqualToString:to] && [from isEqualToString:ROOM_SUFFIX]
        && [iq isResultIQ] && [[iq attributeStringValueForName:@"id"]
                               isEqualToString:GET_ROOMS_ID]){
            // 调用roomListDelegate的方法更新房间列表
            [self.roomListDelegate listRooms:[iq childElement]];

            return YES;
        }
    return NO;
}

// --------------------接收到消息时都会触发该方法,无论是私聊还是群聊--------------------
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
    NSString *to = [message attributeStringValueForName:@"to"];
    NSString *from = [message attributeStringValueForName:@"from"];
    NSString *type = [message attributeStringValueForName:@"type"];
    NSXMLElement *element = [message elementForName:@"body"];
//    [XMPPJID jidWithUser:from domain:HOST_SUFFIX resource:nil];
    // 当用户停留在聊天页面,且收到的信息是正在聊天的对象
    if (self.chatDelegate != nil && [from hasPrefix:[self.chatDelegate getCurrentSession]] && element != nil) {
        [self.chatDelegate didReceiveMessage:message];
    }
    // 这里分两种情况,一是在聊天页面,但不是与收到的信息的对象聊天;二是还没进入聊天页面
    else if ((self.chatDelegate != nil && ![from hasPrefix:[self.chatDelegate getCurrentSession]]) || self.chatDelegate == nil) {
        if ([type isEqualToString:@"chat"] && element != nil) {
//            [self tmpStoreMessage:message from:[XMPPJID jidWithUser:from domain:HOST_SUFFIX resource:nil]];
            [self tmpStoreMessage:message from:[XMPPJID jidWithString:[NSString stringWithFormat:@"%@%@", from, HOST_SUFFIX]]];
        }
    }
    [self.rosterListDelegate refresh];
    NSLog(@"");
}

- (void)tmpStoreMessage:(XMPPMessage *)message from:(XMPPJID *)jid {
    if (self.historyMessage[jid.bare] == nil) {
        self.historyMessage[jid.bare] = [NSMutableArray array];
    }
    [self.historyMessage[jid.bare] addObject:message];
    NSLog(@"done");
}

// MARK: 登录
- (void)goOnline {
    XMPPPresence *presence = [XMPPPresence presence];
    [self.xmppStream sendElement:presence];
}

// MARK: 登出
- (void)goOffline {
    NSLog(@"连接超时");
}

@end
